<template>
  <!--k线-->
  <!-- <div class="k_content" id="kline_kline" style="width: 100%;height: 100%;">
    <div id="main_kline"><div style="color: #fff;">数据正在加载 请稍后...</div></div>
  </div> -->
  <vueKline @initMchar="initMchar" @switchPeriod="changePeriod" @klineInited="initK" ref="kline" :klineParams="klineParams" :klineData="klineDataS" @refreshKlineData="refreshKlineData"></vueKline>
</template>
<script>
import vueKline from '../klinePanel/kline.vue'
import kline from '../kline/kline.js';
import { mapState } from 'vuex';
// import echarts from 'echarts';
// import kline from '../kline/kline.js';
// import data from '../kline/tmpdata.js';
import $ from 'jquery'
import moment from 'moment'
const klineData = {}
export default {
  computed: mapState({
    select: state => state.trade.select /* 当前选中股指 */,
    symbol: state => state.trade.symbol /* 全部行情 */,
    symbos: state => state.trade.symbos /* 当前页面显示行情 */,
    ticket: state => state.trade.ticket /*,, 推送数据 */,
    navtopheight: state => state.navtopheight /* 分隔面板高度 */,
    timelist: state => state.klinetime /* 时间选择器 */,
    klinetab: state => state.klinetab,
    selectData: state => state.trade.selectData,/* 当前选中股指*/
    xuXianData: state => state.xuXianData
  }),
  data() {
    return {
      isLock: false,
      isLine: false,
      last_data: null,
      YJS: 0,
      echarts: null,
      mChart: null,
      range: '',
      kline: null,
      timbar: null,
      klineParams: {
        width: window.innerWidth * .78,
        height: window.innerHeight  - 60,
        theme: "dark",
        language: 'zh-cn',
        ranges: ["1w", "1d", "1h", "30m", "15m", "5m", "1m", "line"],
        symbol: "",
        reverseColor: true,
        debug: false,
        symbolName: "",
        intervalTime: 1000,
        depthWidth: 1
      },
      kData: [],
      klineDataS: {
        success: true,
        data: {
          lines: [
          ]
        }
      },
      time: 1,
      klineInterval: null,
      isright: false,
      mychartkline: null
    };
  },
  beforeDestroy() {
    if (this.klineInterval) {
      clearInterval(this.klineInterval);
    }
    this.klineInterval = null;
  },
  watch: {
    navtopheight: {
      handler: function(val) {
        let h = window.innerHeight - window.innerHeight * ((100 - val) * 0.01)  - 50
        
        if (h > 0) {
          this.klineParams.height = h
          this.kline && this.kline.resize(this.klineParams.width, h)
        }
        if (this.isLine) {
          $('#m-line').css({
            height: (h - 30) + 'px'
          })
          this.mChart.resize()
          
        }
      },
      immediate: true,
　　　 deep:true
    },
    klinetab:function (val) {
      if (val == '1d') {
        val = 'd'
      } else if (val == '1w') {
        val = 'w'
      } else if (val == 'mounth') {
        val = 'm'
      }
      this.init(val.toLocaleUpperCase());
    },
    timelist(val) {
      this.init(val);
    },
   ticket:{
　　　　handler: function(val) {
        
        if (!this.range) {
          return
        }
        if (this.xuXianData.length > 0) {
            let newXu = []
            this.xuXianData.forEach( item => {
                let currentItem = val.find( data => { 
                  return  data.M + data.S + data.C == this.select
                })
                if (currentItem.M + currentItem.S + currentItem.C == item.contract) {
                    let newData = {...item, ...currentItem}
                    newData.yk = this.getYK(newData)
                    newXu.push(newData)
                }
            })
            this.$store.commit('setXuXianData', newXu)
        }
        if (this.isLine) {
          if (this.last_data) {
            // this.myChart && this.myChart.clear();
            // this.mChart.setOption(kline.initMOption(this.last_data, 'us', this.YJS), true);
            // this.mChart.setOption(kline.initMOption(this.last_data, 'us', this.YJS), true);
          }
        }
        // 时间 开盘 最高 最低 收盘 成交量
        // obj['close'] = item[4];
        // obj['date'] = item[0];
        // obj['high'] = item[2];
        // obj['low'] = item[3];
        // obj['open'] = item[1];
        // obj['volume'] = item[5];
        let currentItem = val.find( item => { 
          return  item.M + item.S + item.C == this.select
        })
       
        this.klineParams.symbolName = currentItem.M + currentItem.S + currentItem.C
        this.klineParams.symbol = currentItem.M + currentItem.S + currentItem.C
        let newData = []
        const { M1,M5, M10, M15, M30, H1, YJS } = currentItem
        if (!M1) {
          let klineDataSLine = this.kData
          this.klineDataS.data.lines = klineDataSLine
          return false
        }
        this.YJS = YJS
        let k = null
        if (this.range == '1M') {
          k = M1.split(',')
        } else if (this.range == '5M') {
          k = M5.split(',')
        } else if (this.range == '15M') {
          k = M15.split(',')
        } else if (this.range == '30M') {
          k = M30.split(',')
        } else if (this.range == '1H') {
          k = H1.split(',')
        } else if (this.range == '1D') {
          k = [currentItem.Tick, currentItem.O,currentItem.H,currentItem.L,currentItem.V]
        } else {
          return
        }
        newData[0] = currentItem.Tick * 1000//moment.unix(currentItem.Tick).format('HH:mm')
        newData[1] = parseFloat(parseFloat(k[1]) )
        newData[2] = parseFloat(parseFloat(k[2]) )
        newData[3] = parseFloat(parseFloat(k[3]))
        newData[4] = parseFloat(parseFloat(currentItem.P))
        newData[5] = parseFloat(parseFloat(k[4]) )
        let klineDataSLine = this.kData
        if (klineDataSLine.length > 0 && newData) {
           klineDataSLine[klineDataSLine.length - 1] = newData
           this.klineDataS.data.lines = klineDataSLine
           // this.$refs.kline && this.$refs.kline.redraw(this.klineParams.symbol, this.klineParams.symbolName)
        } 
        
　　　　},
      immediate: true,
　　　 deep:true
　　},
    select:{
　　　　handler: function(val){
        
        this.$nextTick( () => {
            let na = $('.chart_toolbar_tabgroup .selected').parent().attr('name')
            if (!na) {
              this.init('1M');
            } else {
              this.init(na);
            }
            this.$nextTick( () => {
              setTimeout(() => {
               this.kline && this.kline.resize(this.klineParams.width, this.klineParams.height)
               this.klineParams.symbol = val
               this.$refs.kline && this.$refs.kline.redraw(this.klineParams.symbol, this.klineParams.symbolName) 
              }, 1500);
            })
          })
　　　　},
      immediate: true,
　　　　deep:true
　　}
  },
  mounted() {
    $(window).off('resize.cc').on('resize.css',  () => {
      this.kline.resize(window.innerWidth * .78, this.klineParams.height)
    })
  },
  components: {vueKline},
  methods: {
    getYK(item) {
      let dc = 0
      if (!item || !item.N) {
        return dc
      }
      let p = 0
      if (item.risefall == 'rise') {
          if (item.N.indexOf('日元') > -1) {
            dc = isNaN((item.S1 - item.playprice)) ? 0:(item.S1 - item.playprice).toFixed(7)
          } else if (item.N.indexOf('欧元') > -1) {
            dc = isNaN((item.S1 - item.playprice)) ? 0:(item.S1 - item.playprice).toFixed(5)
          } else {
            dc = isNaN((item.S1 - item.playprice)) ? 0:(item.S1 - item.playprice).toFixed(3)
          }
          if (dc == 0) {
            p = 0
           
            return p
          }
        
          if (item.N.indexOf('日元') > -1) {
            p = (parseFloat(dc) / item.unit * item.volume * item.unitprice).toFixed(7)
           
            return  p
          } else if (item.N.indexOf('欧元') > -1) {
            p = (parseFloat(dc) / item.unit * item.volume * item.unitprice).toFixed(5)
           
            return  p
          } else {
            p =  (parseFloat(dc) / item.unit * item.volume * item.unitprice).toFixed(3)
            return p
          }
      } else {
          if (item.N.indexOf('日元') > -1) {
            dc = isNaN((item.playprice - item.B1)) ? 0:(item.playprice - item.B1).toFixed(7)
          } else if (item.N.indexOf('欧元') > -1) {
            dc = isNaN((item.playprice - item.B1)) ? 0:(item.playprice - item.B1).toFixed(5)
          } else {
            dc = isNaN((item.playprice - item.B1)) ? 0:(item.playprice - item.B1).toFixed(3)
          }
          
          if (dc == 0) {
            p = 0
           
            return p
          }
          if (item.N.indexOf('日元') > -1) {
            p = (parseFloat(dc) / item.unit * item.volume * item.unitprice).toFixed(7)
            return  p
          } else if (item.N.indexOf('欧元') > -1) {
            p = (parseFloat(dc) / item.unit * item.volume * item.unitprice).toFixed(5)
           
            return  p
          } else {
            p = (parseFloat(dc) / item.unit * item.volume * item.unitprice).toFixed(3)
           
            return  p
          }
      }
      
    },
    initMchar({mChart, echarts}) {
      this.echarts = echarts
      this.mChart = mChart
    },
    // 更换时间线
    changePeriod(time) {
      this.init(time);
    },
    initK(kline) {
      this.kline = kline
    },
    refreshKlineData(rang) {
    },
    init(range) {
      var that = this;
      if (range == 'line') {
        this.isLine = true
        this.range = '1M'
      } else {
        this.isLine = false
        this.range = range.toUpperCase()
      }
      
      if (that.klineInterval) {
          clearInterval(that.klineInterval);
          that.klineInterval = null;
      }
      
      this.rkline(this.select, this.range);
      let timeSum = 0
      if (this.range == '1M') {
        timeSum = 60000
      } else if (this.range == '5M') {
        timeSum = 300000
      } else if (this.range == '15M') {
        timeSum =  900000
      } else if (this.range == '30M') {
        timeSum =  1800000
      } else if (this.range == '1H') {
        timeSum =  3600000
      } else if (this.range == '1D') {
        timeSum =  86400000
      } else if (this.range == '1W') {
        timeSum =  604800000
      }
      that.klineInterval = setInterval(res => {
        // 进行实时渲染 
          that.rkline(this.select, this.range);
      }, timeSum);
    },
    // 从数组中寻找对应code的数据进行渲染
    // TODO实时动态渲染
    rkline(symbol, time) {
      if (time == '1D') {
        time = 'D'
      }
      if (time == '1W') {
        time = 'W'
      }
      let currentItem = this.ticket.find( item => { 
        return  item.M + item.S + item.C == this.select
      })
      this.klineParams.symbolName = currentItem.M + currentItem.S + currentItem.C
      this.klineParams.symbol = currentItem.M + currentItem.S + currentItem.C
       if (this.isLine) { 
          $('#buy_line').remove()
          $('#sell_line').remove()
          if (document.querySelector('#chart_overlayCanvas')) document.querySelector('#chart_overlayCanvas').style.display = 'none'
          if (document.querySelector('#chart_mainCanvas')) document.querySelector('#chart_mainCanvas').style.display = 'none'
      }
      // this.isLock = true
      this.$post('kvc/socketlist', {
        symbol: symbol,
        period: time,
        pidx: 1,
        psize: time == 'W'  ? 50:200,
        withlast: 1
      }).then(res => {
        let data = JSON.parse(res.data)
        if (data.Code == 0) {
          let last_data = []
          let arr = data.Obj.split(';')
          arr.sort((a,b) => {
            return parseFloat(a.split(',')[0]) - parseFloat(b.split(',')[0])
          }).forEach( (item,index) => {
            let datas = item.split(',')
            let num = parseInt(datas[6] || 0)
            let money = parseFloat(datas[5] || 0)
            if ((!num && money) || (num && !money)) {
              return
            }
            let tick = datas[0]
            let time1 = moment(tick * 1000).format('HH:mm') // 时间
            let ds = []
            if (this.isLine) {
              ds.push(time1);
              ds.push(parseFloat(datas[1])); // 当前价
              if (currentItem.N.indexOf('日元') > -1) {
                ds.push(parseFloat((num ? parseFloat(money / num) : parseFloat(datas[1])).toFixed(7))  );
              } else if (currentItem.N.indexOf('欧元') > -1) {
                ds.push(parseFloat((num ? parseFloat(money / num) : parseFloat(datas[1])).toFixed(5)) );
              } else {
                ds.push(parseFloat( (num ? parseFloat(money / num) : parseFloat(datas[1])).toFixed(3) ) );
              }
              ds.push(parseFloat(datas[6]));
              last_data.push(ds)
            } else {
              
              // 时间 开盘 最高 最低 收盘 成交量
              ds.push(tick * 1000)
              ds.push(parseFloat(datas[2])); // 开盘价
              ds.push(parseFloat(datas[3]) ); // 最高
              ds.push(parseFloat(datas[4]));
              ds.push(parseFloat(datas[1]));
              ds.push(parseFloat(datas[6]));
              last_data.push(ds)
            }
            
          })
          if (this.isLine) {
            $('.charBox').show()
            if (document.querySelector('.drawBox'))  document.querySelector('.drawBox').style.display = 'none'
            if (document.querySelector('#chart_overlayCanvas')) document.querySelector('#chart_overlayCanvas').style.display = 'none'
            this.$nextTick( () => {
              if (document.querySelector('#chart_tabbar')) document.querySelector('#chart_tabbar').style.display = 'none'
              if (document.querySelector('.m-line')) document.querySelector('.m-line').style.display = 'block';
              if (document.querySelector('#chart_mainCanvas')) document.querySelector('#chart_mainCanvas').style.display = 'none'
              // arr = lines
              // 请求获取虚线数据
              this.last_data = last_data
              let h = window.innerHeight - window.innerHeight * ((100 - this.navtopheight) * 0.01)  - 50
              $('#m-line').css({
                height: (h - 30) + 'px'
              })
              this.myChart && this.myChart.clear();
              if (this.YJS) {
                this.mChart.setOption(kline.initMOption(last_data, 'us', this.YJS), false);
              } else {
                setTimeout( () => {
                this.mChart.setOption(kline.initMOption(last_data, 'us', this.YJS), false);
              }, 1000)
              }
              
              
              // this.mChart && this.mChart.resize()
              $(window).off('resize.oooo').on('resize.oooo', () => {
                  this.mChart.resize()
              })
              
            })
          } else {
            $('.charBox').hide()
            if (document.querySelector('.drawBox'))  document.querySelector('.drawBox').style.display = 'block'
            if(document.querySelector('.m-line'))  document.querySelector('.m-line').style.display = 'none'
            this.$nextTick( () => {
                if (document.querySelector('#chart_tabbar')) document.querySelector('#chart_tabbar').style.display = 'block'
                if(document.querySelector('#chart_overlayCanvas')) document.querySelector('#chart_overlayCanvas').style.display = 'block'
                if(document.querySelector('#chart_mainCanvas')) document.querySelector('#chart_mainCanvas').style.display = 'block'
                // this.klineDataS.data.lines = last_data
                this.kData = last_data
                // this.$refs.kline && this.$refs.kline.redraw(this.klineParams.symbol, this.klineParams.symbolName)
                // setTimeout( () => {
                //   this.isLock = false
                // }, 300)
                
                // 请求获取虚线数据
                this.$post('order/linedata', {
                  contract: symbol
                }).then( res => {
                  this.$store.commit('setXuXianData', res.data)
                })
            }) 
          }
          
          
          
          // this.mychartkline.setOption(kline.initKOption(this.klineData));
        } else {
          if (this.klineInterval) {
            clearInterval(this.klineInterval);
          }
          this.klineInterval = null;
          // this.mychartkline.setOption(kline.initKOption(data.knedata0));
        }
      });
    }
  }
};
</script>

<style scoped></style>
